import json
import FacePlusPlusAPI
import os
import base64

# Initialize some variables
facePP_API_Key = 'Dh_1F9Ax2b5feD7KkAc0nu46v3CVnRRX'
facePP_API_Secret = 'VYKh8ciikCPCrbg4Lm2iuJrcxouqDNXP'

def getFaceName(fileName):
    dotIndex = fileName.index('.')
    return fileName[:dotIndex]

def getBASE64(image):
    return base64.b64encode(image)

if __name__ == '__main__':
    jsonFL = json.load(open('faces_list.json', 'r'))

    local_face_list = os.listdir('faces')
    for face in local_face_list:
        image_as_text = getBASE64(open('faces\\' + face, 'rb').read())
        result = FacePlusPlusAPI.faceppDetectAPI_base64(
            facePP_API_Key, facePP_API_Secret, image_as_text
        )
        token = result[0]["face_token"]
        name = getFaceName(face)
        if name not in jsonFL["face2token"]:
            jsonFL["face2token"].update({name: [token]})
        else:
            jsonFL["face2token"][name].append(token)
        if token not in jsonFL["token2face"]:
            jsonFL["token2face"].update({token: name})

    json.dump(jsonFL, open('faces_list.json', 'w'))

    for token in jsonFL["token2face"].keys():
	    FacePlusPlusAPI.addToFaceSet(facePP_API_Key, facePP_API_Secret, 'test', token)
